﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;

namespace Infrastructure.Crosscutting.NetFramework.Result
{
    public class CustomJsonResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;
            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                var res = serializer.Serialize(Data);
                res = Regex.Replace(res, @"\\/Date\((\d+)\)\\/", match =>
           {
               DateTime dt = new DateTime(1970, 1, 1);
               dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
               dt = dt.ToLocalTime();
               return dt.ToString("yyyy-MM-dd HH:mm:ss");
           });
                response.Write(res);
            }
        }
    }
}
